﻿using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WeatherHistory.Api.CommandsQueries.Commands.Accounts.Authentication;
using WeatherHistory.Shared.Constants;
using WeatherHistory.Shared.Helpers;

namespace WeatherHistory.Api.Controllers;

/// <summary>
///     Контроллер аутентификации
/// </summary>
[AllowAnonymous]
[Route("login")]
public class LoginController : ApiControllerBase
{
    /// <summary>Аутентификация</summary>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    public async Task<ActionResult<AuthenticationAccountsCommandResponse>> Post([FromBody] AuthenticationAccountsCommandRequest query)
    {
        var currentUserId = HttpContext.Request.Cookies["id"];
        if (currentUserId != null) return Ok(new AuthenticationAccountsCommandResponse { Id = long.Parse(currentUserId) });

        var result = await Mediator.Send(query);
        SecurityHelper.AuthenticateWithCookie(HttpContext, result.Id);
        return Ok(result);
    }
}